package com.tx.studentManager.service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.util.StringUtils;

import com.tx.studentManager.model.UrlFilter;


/**
 * 
* 【Shiro Url连接管理服务】
* @since studentManager-admin 1.0.2
* @version 1.0.2
* @date 2015年9月27日 上午9:24:04
* @author 此生唯晴
 */
//@Component
public class ShiroFilterChainService {

//	@Autowired
	private AbstractShiroFilter shiroFilter;
//	@Autowired
//	private UrlFilterService urlFilterService;
   
    private DefaultFilterChainManager filterChainManager;

    private Map<String, NamedFilterList> defaultFilterChains;
    Logger logger=Logger.getLogger(ShiroFilterChainService.class);

//    @PostConstruct
    public void init() {
    	PathMatchingFilterChainResolver filterChainResolver=(PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
    	filterChainManager=(DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
        //使用LinkedHashMap保证url存储顺序
    	defaultFilterChains = new LinkedHashMap<String, NamedFilterList>(filterChainManager.getFilterChains());
    }

    /**
     * 
     * @描述 初始化url权限或改动后重新加载 
     * @param urlFilters
     */
    public void initFilterChains(List<UrlFilter> urlFilters) {
//    	logger.debug("【原chain】:\n"+filterChainManager.getFilterChains());
        //首先删除以前老的filter chain并注册默认的
        filterChainManager.getFilterChains().clear();
        
        if(defaultFilterChains != null) {
        	logger.debug("FilterChains:\n"+defaultFilterChains);
            filterChainManager.getFilterChains().putAll(defaultFilterChains);
        }

        //循环URL Filter 注册filter chain
        for (UrlFilter urlFilter : urlFilters) {
            String url = urlFilter.getUrl();
            //注册roles filter
            if (!StringUtils.isEmpty(urlFilter.getRoles())) {
                filterChainManager.addToChain(url, "roles", urlFilter.getRoles());
            }
            //注册perms filter
            if (!StringUtils.isEmpty(urlFilter.getPermission())) {
                filterChainManager.addToChain(url, "perms", urlFilter.getPermission());
            }
        }
        //添加对所有资源的认证控制
        filterChainManager.addToChain("/**", "authc");
    }

	public AbstractShiroFilter getShiroFilter() {
		return shiroFilter;
	}

	public void setShiroFilter(AbstractShiroFilter shiroFilter) {
		this.shiroFilter = shiroFilter;
	}
    
}
